c++ string常用函数总结

c++string常用函数

构造函数

string(const char *s); //用c字符串s初始化
string(int n,char c); //用n个字符c初始化
此外,string类还支持默认构造函数和复制构造函数,如string s1;
string s2=”hello”;都是正确的写法。当构造的string太长而无法表达时会抛出length_error异常 ;

string的特性描述:

int capacity()const; //返回当前容量(即string中不必增加内存即可存放的元素个数)
int max_size()const; //返回string对象中可存放的最大字符串的长度
int size()const; //返回当前字符串的大小
int length()const; //返回当前字符串的长度
bool empty()const; //当前字符串是否为空
void resize(int len,char c);//把字符串当前大小置为len,并用字符c填充不足的部分

子串

1
string substr (size_t pos = 0, size_t len = npos) const;

第一个参数默认为0,第二参数默认为字符串结尾的下一个字符。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <string>

int main ()
{
std::string str="We think in generalities, but we live in details.";

std::string str2 = str.substr (3,5); // "think"

std::size_t pos = str.find("live"); // position of "live" in str

std::string str3 = str.substr (pos); // get from "live" to the end

std::cout << str2 << ' ' << str3 << '\n';

return 0;
}

查找类型

(1) find,rfind这种函数匹配的是指定的连续的数列(当查找的是字符串时),当参数为字符时,查找的是这个字符出现的位置

1
2
3
4
5
6
7
8
string (1)	
size_t find (const string& str, size_t pos = 0) const;
c-string (2)
size_t find (const char* s, size_t pos = 0) const;
buffer (3)
size_t find (const char* s, size_t pos, size_t n) const;
character (4)
size_t find (char c, size_t pos = 0) const;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>       // std::cout
#include <string> // std::string

int main(){
std::string str ("There are two needles in this haystack with needles.");
std::string str2 ("needle");

// different member versions of find in the same order as above:
std::size_t found = str.find(str2);
if (found!=std::string::npos)
std::cout << "first 'needle' found at: " << found << '\n';
//这里可以指定匹配的字符串的长度,下面的例子匹配长度为6,也就是匹配needle
found=str.find("needles are small",found+1,6);
if (found!=std::string::npos)
std::cout << "second 'needle' found at: " << found << '\n';

found=str.find("haystack");
if (found!=std::string::npos)
std::cout << "'haystack' also found at: " << found << '\n';

found=str.find('.');
if (found!=std::string::npos)
std::cout << "Period found at: " << found << '\n';

// let's replace the first needle:
str.replace(str.find(str2),str2.length(),"preposition");
std::cout << str << '\n';

return 0;
}

(2) find_first_of,find_first_not_of,find_last_of,find_last_not_of
上面的这四个函数匹配的是给定范围的任意字符,例如

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>       // std::cout
#include <string> // std::string
#include <cstddef> // std::size_t

int main ()
{
std::string str ("Please, replace the vowels in this sentence by asterisks.");
std::size_t found = str.find_first_of("aeiou");
while (found!=std::string::npos)
{
str[found]='*';
found=str.find_first_of("aeiou",found+1);
}

std::cout << str << '\n';

return 0;
}

1
Pl**s*, r*pl*c* th* v*w*ls *n th*s s*nt*nc* by *st*r*sks.

其它成员函数详见
http://www.cplusplus.com/reference/string/string/